/*=====================================================================
  This file is part of a Microsoft SQL Server Shared Source Application.
  Copyright (C) Microsoft Corporation.  All rights reserved.
 
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
======================================================= */

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/* This class will be used for databinding an xml file to a parameter in a web test */
namespace LoaderPlugin
{
	public class XmlDS
	{
		// singleton instance
		private static readonly XmlDS m_instance = new XmlDS();
		
		// keep track of last user
		private int m_nextPosition = 0;
		
		private bool m_initialized = false;
		private DataSet m_datasource;
		private static readonly object m_Padlock = new object();
        
        static XmlDS()
		{
		}

        public static XmlDS Instance
		{
			get
			{
				return m_instance;
			}
		}

		public bool Initialized
		{
			get
			{
				return m_initialized;
			}
			
		}

		public void Initialize(string fileName)
		{
			lock (m_Padlock)
			{
				if (m_datasource == null && Initialized==false)
				{
					// load the data
					FileInfo fi = new FileInfo(fileName);

                    if (!fi.Exists)
					{
                        throw new Exception("File '" + fileName + "' does not exist.");
					}

                    m_datasource = new DataSet();
                    m_datasource.ReadXml(fileName);
            						                    
					// set the manager to initialized
					m_initialized = true;										
				}
			}
		}

		public Dictionary<String,String> GetNextRow()
		{
			if (m_datasource != null)
			{
				// lock the thread
				lock (m_Padlock)
				{
                    if (m_nextPosition == m_datasource.Tables[0].Rows.Count)
                    {
                        m_nextPosition = 0;
                    }

                    Dictionary<String, String> dictionary = new Dictionary<string, string>();

                    foreach (DataColumn c in m_datasource.Tables[0].Columns)
                    {
                        dictionary.Add(c.ColumnName, m_datasource.Tables[0].Rows[m_nextPosition][c].ToString());
                    }
                    m_nextPosition++; 
                    
                    return dictionary;
				}
			}

			return null;
		}
	}
}